package com.example.spring_blog_24_9_8.controller;

import com.example.spring_blog_24_9_8.model.Result;
import com.example.spring_blog_24_9_8.model.User;
import com.example.spring_blog_24_9_8.service.UserService;
import com.example.spring_blog_24_9_8.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse
            response, String username, String password){
        if (!StringUtils.hasLength(username) ||
                !StringUtils.hasLength(password)){
            log.error("username:"+username+",password:"+password);
            return Result.fail(-1, "⽤⼾名或密码为空");
        }
        //判断账号密码是否正确
        User user = userService.getUserInfo(username);
        if (user==null || !user.getPassword().equals(password)){
            return Result.fail(-1, "⽤⼾名或密码错误");
        }
        //登录成功, 返回token
        log.info("可能登录成功，登录成功, 返回token");
        Map<String , Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUserName());
        String token = JwtUtils.genToken(claims);
        System.out.println("⽣成token:"+ token);
        log.info("已经生成了token");
        log.info("result.success"+Result.success(token));
        return Result.success(token);
    }

    /**
     * 获取当前登录⽤⼾信息
     * @param request
     * @return
     */
    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request){
        //从header中获取token
        String jwtToken = request.getHeader("user_token");
        //从token中获取⽤⼾id
        Integer userId = JwtUtils.getUserIdFromToken(jwtToken);
        //根据Userid获取⽤⼾信息
        if (userId!=null){
            return userService.selectById(userId);
        }
        return null;
    }

    /**
     * 获取博客作者信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer blogId) {
        if (blogId == null && blogId < 1) {
            return Result.fail(-1, "博客ID不正确");
        }
        //根据博客id, 获取作者相关信息
        User user = userService.selectAuthorByBlogId(blogId);
        return Result.success(user);
    }
}